// 1. React核心库
import React, { useState, useRef, useCallback } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, message, Modal, Space, Tag, Popconfirm } from 'antd';

// 3. 图标库
import { PlusOutlined, EditOutlined, DeleteOutlined, CopyOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable, ProColumns, ActionType } from '@ant-design/pro-components';

// 5. 工具库
 
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import TemplateForm from './components/TemplateForm';
import TemplateDetail from './components/TemplateDetail';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { MessageTemplate } from '@/services/generated';

const MessageTemplateList: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<MessageTemplate | null>(null);
  const actionRef = useRef<ActionType>();

  // 获取模板列表
  const fetchTemplates =  
    async (params: any) => {
      try {
        await autoLoginInDev();
        const response = await apiClients.aiChat.aiChatTemplatesList({
          page: params.current,
          pageSize: params.pageSize,
          search: params.search,
          category: params.category,
          isPublic: params.is_public,
        });
        return {
          data: response.data?.items || [],
          success: true,
          total: response.data?.total || 0,
        };
      } catch (error) {
        message.error('获取数据失败');
        return { data: [], success: false, total: 0 };
      }
    } 

  // 删除模板
  const handleDelete = useCallback(async (id: number) => {
    try {
      await autoLoginInDev();
      await apiClients.aiChat.aiChatTemplatesDestroy({ id: String(id) });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  }, []);

  // 复制模板内容
  const handleCopy = useCallback(async (content: string) => {
    try {
      await navigator.clipboard.writeText(content);
      message.success('模板内容已复制到剪贴板');
    } catch (error) {
      message.error('复制失败');
    }
  }, []);

  // 表格列定义
  const columns: ProColumns<MessageTemplate>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '模板名称',
      dataIndex: 'name',
      ellipsis: true,
      formItemProps: {
        rules: [{ required: true, message: '请输入模板名称' }],
      },
    },
    {
      title: '分类',
      dataIndex: 'category',
      valueType: 'select',
      valueEnum: {
        prompt: { text: '提示词', status: 'Processing' },
        question: { text: '问题', status: 'Success' },
        instruction: { text: '指令', status: 'Warning' },
        creative: { text: '创意', status: 'Default' },
        technical: { text: '技术', status: 'Error' },
      },
      render: (_, record) => {
        const categoryMap = {
          prompt: { color: 'blue', text: '提示词' },
          question: { color: 'green', text: '问题' },
          instruction: { color: 'orange', text: '指令' },
          creative: { color: 'purple', text: '创意' },
          technical: { color: 'red', text: '技术' },
        };
        const category = categoryMap[record.category as keyof typeof categoryMap];
        return <Tag color={category?.color}>{category?.text || record.category}</Tag>;
      },
    },
    {
      title: '模板内容',
      dataIndex: 'content',
      ellipsis: true,
      search: false,
      width: 200,
    },
    {
      title: '使用次数',
      dataIndex: 'usage_count',
      search: false,
      sorter: true,
      render: (value) => (
        <Tag color="purple">{value || 0} 次</Tag>
      ),
    },
    {
      title: '公开',
      dataIndex: 'is_public',
      valueType: 'select',
      valueEnum: {
        true: { text: '公开', status: 'Processing' },
        false: { text: '私有', status: 'Default' },
      },
      render: (_, record) => (
        <Tag color={record.is_public ? 'blue' : 'default'}>
          {record.is_public ? '公开' : '私有'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
      sorter: true,
      render: (_, record) => {
        if (!record.created_at) return '-';
        const date = dayjs(record.created_at);
        return date.isValid() ? date.format('MM-DD HH:mm') : '-';
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 220,
      render: (_, record) => [
        <Button
          key="copy"
          type="link"
          size="small"
          icon={<CopyOutlined />}
          onClick={() => handleCopy(record.content || '')}
        >
          复制
        </Button>,
        <Button
          key="detail"
          type="link"
          size="small"
          onClick={() => {
            setCurrentRecord(record);
            setDetailModalVisible(true);
          }}
        >
          详情
        </Button>,
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => {
            setCurrentRecord(record);
            setEditModalVisible(true);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除这个模板吗？"
          onConfirm={() => handleDelete(record.id!)}
          okText="确定"
          cancelText="取消"
        >
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
          >
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '消息模板管理',
        subTitle: '管理常用的消息模板和提示词',
      }}
    >
      <ProTable<MessageTemplate>
           scroll={{x: 'max-content'}}
        headerTitle="消息模板列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setCreateModalVisible(true)}
          >
            新建模板
          </Button>,
        ]}
        request={fetchTemplates}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
        }}
      />

      {/* 新建模板Modal */}
      <Modal
        title="新建消息模板"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={800}
      >
        <TemplateForm
          onSubmit={async (values) => {
            try {
              await autoLoginInDev();
              await apiClients.aiChat.aiChatTemplatesCreate({ messageTemplateRequest: values });
              message.success('创建成功');
              setCreateModalVisible(false);
              actionRef.current?.reload();
            } catch (error) {
              message.error('创建失败');
            }
          }}
          onCancel={() => setCreateModalVisible(false)}
        />
      </Modal>

      {/* 编辑模板Modal */}
      <Modal
        title="编辑消息模板"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        width={800}
      >
        <TemplateForm
          initialValues={currentRecord || undefined}
          onSubmit={async (values) => {
            try {
              await autoLoginInDev();
              await apiClients.aiChat.aiChatTemplatesUpdate({
                id: String(currentRecord!.id),
                messageTemplateRequest: values
              });
              message.success('更新成功');
              setEditModalVisible(false);
              setCurrentRecord(null);
              actionRef.current?.reload();
            } catch (error) {
              message.error('更新失败');
            }
          }}
          onCancel={() => {
            setEditModalVisible(false);
            setCurrentRecord(null);
          }}
        />
      </Modal>

      {/* 模板详情Modal */}
      <Modal
        title="消息模板详情"
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setCurrentRecord(null);
        }}
        footer={null}
        width={800}
      >
        <TemplateDetail 
          template={currentRecord}
          onCopy={handleCopy}
        />
      </Modal>
    </PageContainer>
  );
};

export default MessageTemplateList;
